<?php
require_once('../../core.inc.php');
require_once('Model/SiteManage.php');
require_once('View/Smarty.php');
require_once('Model/DB.php');
require_once('Model/Validate.php');
require_once('Model/Pager.php');
require_once('Model/Uploader.php');
require_once('Plugin/Seo.php');

$sys = new Model_SiteManage();
$sys->checkLogin();
$params       = $_REQUEST;
$smarty       = new View_Smarty($params);
$seo = new Model_Seo();
$smarty->assign('seo', $seo);

//var_dump($params);

if (isset($params['do']) && function_exists('exec_' . $params['do'])){
   $params['op'] = call_user_func('exec_' . $params['do'], &$params, &$smarty, &$seo);
}
if (isset($params['op']) && function_exists('op_' . $params['op'])){
    call_user_func('op_' . $params['op'], $params, &$smarty, &$seo);
}
else{
    call_user_func('op_search', $params, &$smarty, &$seo);
}


function op_search($params, &$smarty, &$seo)
{
    if (!isset($params['search'])){
        $search             = array();
        $search['keyword']  = '';
        $search['url']      = '';
        $params['search']   = $search;
    }else{
        $page_id = isset($params['page_id']) && $params['page_id'] > 1 ? $params['page_id'] : 1;
        $max_row = 20;
        $pager   = new Model_Pager();
        $pager->getPagerInfo($seo->getListCount($params['search']), $page_id, $max_row);
        $list = $seo->getList($params['search'], 'id asc', $max_row, ($max_row * ($page_id - 1)));
        $smarty->assign('list', $list);
        $smarty->assign('pager', $pager);
    }
    
    $smarty->assign('search', $params['search']);
    $smarty->display('seo/seo_index.html');
}

// 新規登録
function op_regist($params, &$smarty, &$seo)
{
    if (!isset($params['forms'])){
        $forms = array();
        foreach($seo->getFormKeys() as $key){
            $forms[$key] = '';
        }
        //var_dump($forms);
        $params['forms'] = $forms;
    }
    else{
        /*必要？
        $keys = explode(',', 'status,class_id,park_flag');
        foreach($keys as $key){
            if (!isset($params['forms'][$key])){
                $params['forms'][$key] = '';
            }
        }
         */
    }
    $smarty->assign('phase', 'input');
    $smarty->assign('forms', $params['forms']);
    $smarty->display('seo/seo_form.html');
//print_r($params);
}

function exec_validate_regist_form(&$params, &$smarty, &$seo)
{
    //var_dump($params);
    $err = array();

    if ($seo->validate($params['forms'], $err)){
        return exec_regist_form($params, $smarty, $seo);
    }
    $validate = new Model_Validate();
    $smarty->assign('validate', $validate);
    $smarty->assign('err', $err);
//print_r($err);
    return 'regist';
}
function exec_regist_form(&$params, &$smarty, &$seo)
{
    $id = $seo->insert($params['forms']);
    header('Location: '. $_SERVER['SCRIPT_NAME'] . '?op=regist_complete&id=' . $id);
    exit();
}

function op_regist_complete($params, &$smarty, &$seo)
{
    $smarty->assign('phase', 'complete');
    if(isset($params['id'])){
        $smarty->assign('id', $params['id']);
        $smarty->assign('forms', array('id' => $params['id']));
    }
    $smarty->assign('message', '登録が完了しました');
    $smarty->display('seo/seo_form.html');
}

// 編集
function op_edit($params, &$smarty, &$seo)
{
    if (!isset($params['id'])){
        __raise_error();
    }
    //var_dump($params);
    $id = $params['id'];
    if (!isset($params['forms'])){
        $forms = $seo->get($id);
        $params['forms']   = $forms;
    }
    else{
        /*必要？
        $keys = explode(',', 'status,class_id,park_flag');
        foreach($keys as $key){
            if (!isset($params['forms'][$key])){
                $params['forms'][$key] = '';
            }
        }
         */
    }
    $smarty->assign('id', $id);
    $smarty->assign('phase', 'input');
    $smarty->assign('forms', $params['forms']);
    $smarty->display('seo/seo_form.html');
}

function exec_validate_update_form(&$params, &$smarty, &$seo)
{
    if (!isset($params['id'])){
        __raise_error();
    }else{
       $params['forms']['id'] = $params['id'];
    }
    $err = array();
    if ($seo->validate($params['forms'], $err)){
        return exec_update_form($params, $smarty, $seo);
    }
    $validate = new Model_Validate();
    $smarty->assign('validate', $validate);
    $smarty->assign('err', $err);
    return 'edit';
}
function exec_update_form(&$params, &$smarty, &$seo)
{
    $id = $params['id'];
    
	if($_POST['mode'] == "delete")
	{
		$params['forms']['enabled'] = 0;
	}
	
    $seo->update($id, $params['forms']);
    header('Location: '. $_SERVER['SCRIPT_NAME'] . '?op=edit_complete&id=' . $id);
    exit();
}
function op_edit_complete($params, &$smarty, &$seo)
{
    $smarty->assign('phase', 'complete');
    if(isset($params['id'])){
        $smarty->assign('id', $params['id']);
        $smarty->assign('forms', array('id' => $params['id']));
    }
    $smarty->assign('message', '更新が完了しました');
    $smarty->display('seo/seo_form.html');
}

// 参照
function op_refer($params, &$smarty, &$seo)
{
    if (!isset($params['id'])){
        __raise_error();
    }
    $id = $params['id'];
    if (!isset($params['forms'])){
        $forms = $seo->get($id);
        $params['forms']   = $forms;
    }

    //デモデータ
    $demo = array();
//    $base_rank = ($forms['rank'] != '' ? (int)$forms['rank'] : 100);
//    if($base_rank < 5){
//         $base_rank += 2;
//    }
//    if($base_rank < 100){
//        $range = $base_rank / 2;
//    }
//    else{
//        $range = $base_rank / 10;
//    }
//
//    for($i=10; $i>0; $i--){
//        $d = date("Y-m-d", time() - 60*60*24* $i);
//        $demo[$d] = array(
//                'google' => $base_rank + rand(-1 * $range,$range *0.5),
//                'yahoo'  => $base_rank + rand(-1 * $range,$range *0.5)
//                );
//    }
    $db = new Model_DB();
    $sql = "select rank, date_format(r_date, '%Y-%m-%d') as r_date from D_SEO_RANK where search_engine = 'Google' and seo_id = '" . $db->escape($id) . "' ORDER BY r_date";
    $db->query($sql);
    while($data = $db->fetch())
    {
        $demo[$data['r_date']]['google'] = $data['rank'];
    }
    
    $sql = "select rank, date_format(r_date, '%Y-%m-%d') as r_date from D_SEO_RANK where search_engine = 'yahoo' and seo_id = '" . $db->escape($id) . "' ORDER BY r_date";
    $db->query($sql);
    while($data = $db->fetch())
    {
        $demo[$data['r_date']]['yahoo'] = $data['rank'];
    }
    
    //var_dump($demo);exit;
    $smarty->assign('demo', $demo);
    
    $smarty->assign('id', $id);
    $smarty->assign('phase', 'input');
    $smarty->assign('forms', $params['forms']);
    $smarty->display('seo/seo_refer.html');
}

// CSVダウンロードdemo
function op_csv($params, &$smarty, &$seo)
{
    if (!isset($params['id'])){
        __raise_error();
    }
    $id = $params['id'];
    $forms = $seo->get($id);

        $filename = mb_convert_encoding($forms['keyword'].'('. $forms['url'] .')'.'.csv', 'SJIS-WIN', 'UTF-8');
        header('Content-disposition: attachment; filename='. $filename);
        header('Content-Type: text/csv; charset=Shift_JIS');
        echo(mb_convert_encoding('日付,Google,Yahoo', 'SJIS-WIN', 'UTF-8')."\n");
        foreach($_POST['google'] as $d => $r){
            $row = array(
                    $d,
                    $r,
                    $_POST['yahoo'][$d]
                    );
            echo(mb_convert_encoding( implode(',', $row), 'SJIS-WIN', 'UTF-8'). "\n");
        }
        exit();
}
?>